﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Modeling;
using System.Diagnostics;
using System.Drawing;
using System.Collections;

namespace DSLFactory.VSCTDesigner
{
    [RuleOn(typeof(Bitmap), FireTime = TimeToFire.TopLevelCommit)]
    class BitmapChangeRule : ChangeRule
    {
        /// <summary>
        /// Calcul de la liste des images disponibles dans usedList
        /// </summary>
        /// <param name="e"></param>
        public override void ElementPropertyChanged(ElementPropertyChangedEventArgs e)
        {
            if( e.ModelElement.Store.InUndoRedoOrRollback || e.ModelElement.Store.TransactionManager.CurrentTransaction.IsSerializing )
                return;

            // Calcul de la liste des images disponibles dans usedList
            if( e.DomainProperty.Id == Bitmap.hRefDomainPropertyId || e.DomainProperty.Id == Bitmap.resIdDomainPropertyId )
            {
                Bitmap bmp = e.ModelElement as Bitmap;
                string oldUsedListValue = bmp.usedList;

                List<string> symbolsToCreate = new List<string>();
                Image img = bmp.ResolveImage(null);
                if( img == null )
                {
                    bmp.usedList = String.Empty;
                }
                else
                {
                    int nb = img.Size.Width / 16;
                    StringBuilder sb = new StringBuilder();
                    for( int ix = 1; ix <= nb; ix++ )
                    {
                        if( ix > 1 && ix <= nb )
                            sb.Append(", ");
                        string id = "Pict" + ix;
                        sb.Append(id);
                        symbolsToCreate.Add(id);
                    }
                    bmp.usedList = sb.ToString();
                }

                if( !String.IsNullOrEmpty(oldUsedListValue) )
                {
                    string[] iDs = oldUsedListValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach( string id in iDs )
                    {
                        if( !symbolsToCreate.Contains(id) )
                            GuidSymbolHelper.RemoveIDSymbol(bmp, id.Trim());
                    }
                }
                
                foreach( var id in symbolsToCreate )
                    GuidSymbolHelper.EnsureIDSymbol(bmp, id);
            }

            // Modification de l'id du bitmap sur les commandes dépendantes
            if( e.DomainProperty.Id == Bitmap.usedListDomainPropertyId )
            {
                string[] values = ((string)e.NewValue).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                for( int i = 0; i < values.Length; i++ )
                    values[i] = values[i].Trim();
                    
                Bitmap bitmap = e.ModelElement as Bitmap;
                foreach( var relationShip in CommandHasIcon.GetLinksToCommand(bitmap))
                {
                    if( values.Length == 0 || !values.Contains(relationShip.IconId, StringComparer.CurrentCultureIgnoreCase) )
                        relationShip.IconId = String.Empty;
                }
            }
        }
    }

    [RuleOn(typeof(Bitmap), FireTime = TimeToFire.TopLevelCommit)]
    class BitmapDeleteRule : DeleteRule
    {
        public override void ElementDeleted(ElementDeletedEventArgs e)
        {
            Bitmap bmp = e.ModelElement as Bitmap;
            var commandTable = bmp.Store.ElementDirectory.FindElements<CommandTable>().FirstOrDefault();
            GuidSymbolHelper.RemoveGuidSymbol(commandTable, bmp.Guid);
        }
    }

}
